package Prova::Controller::Recorder;

use strict;
use warnings;
use base 'Catalyst::Controller';
use Constants;
use YAML;
use Data::Dumper;

=head1 NAME

Prova::Controller::Recorder - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=head2 default

default action

=cut

sub default : Private {
    my ( $self, $c, $params, $testcase ) = @_;

    unless ($c->stash->{'no_check'}) {
        die "host is null" unless $c->req->param('host');
        my $account = $c->model('DBIC::Account')->find( host => $c->req->param('host') );
        die "account is null" unless defined $account;
        die "recording is 0" unless $account->recording;
    }

    $testcase = $c->forward('/testcase/is_recording') unless $testcase;
    $testcase = $c->forward('/testcase/start_recording') unless $testcase;

    $params = $c->req->params if ref $params ne 'HASH';

    if ( ref $params eq 'HASH' and keys %$params ) {
        my %datablock;
        my $cnt = 1;
        my %datasections;
        for my $key ( keys %$params ) {
            if ( $key eq 'block_path' ) {
                $datablock{path} = $params->{$key};
            }
            if ( $key eq 'query' ) {
                $datablock{query} = $params->{$key};
            }
            elsif ( $key eq 'block_method' ) {
                $datablock{method} = $params->{$key};
            }
            elsif ( $key =~ /^section_(.*)/ ) {
                $datasections{$cnt} = { name => $1, value => $params->{$key} };
            }
            else {

                # nothing to do.
            }
            $cnt++;
        }

        # regist data_block
        $c->stash->{testcase} = $testcase;
        $datablock{engine}    = Constants->ENGINE_MECHANIZE;
        $c->stash->{data}     = \%datablock;
        $c->forward('/datablock/create');

        # regist uploaded files
        for my $key ( keys %$params ) {
            if ( $key =~ /^upload_(.*)/ ) {
                my $name = $1;
                undef $c->stash->{file};
                $c->stash->{file} = Load $params->{$key};
                $c->forward('/file/create');
                foreach ( keys %datasections ) {
                    if ( $datasections{$_}->{name} eq $name ) {
                        $datasections{$_}->{value} = $c->stash->{file}->path;
                    }
                }
            }
        }

        # regist data_section
        $c->stash->{datasection} = \%datasections;
        $c->forward('/datasection/create');
    }

    unless ($c->stash->{'no_check'}) {
        $c->res->status(200);
        $c->res->body("200 OK\n");
    }
}

=head1 AUTHOR

Shanon Inc, E<lt>http://www.shanon.co.jp/E<gt>

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
